﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Drawing;
using System.Net;

namespace NekoVampire.TwitterClient.Twitter
{
    public class Storage
    {
        public List<Status> timeLine;
        private Dictionary<String, Bitmap> profileImage;
        private List<int>[] ids;

        public Storage()
        {
            ids = new List<int>[]
            {
                new List<int>(),
                new List<int>(),
                new List<int>()
            };
            timeLine = new List<Status>();
            profileImage = new Dictionary<string, Bitmap>();
        }
        
        public List<int> friends
        {
            get
            {
                return ids[0];
            }
            private set
            {
                ids[0] = value;
                notFollow = friends.Except(followers).ToList();
            }
        }
        public List<int> followers
        {
            get
            {
                return ids[1];
            }
            private set
            {
                ids[1] = value;
                notFollow = friends.Except(followers).ToList();
            }
        }
        public List<int> notFollow
        {
            get
            {
                return ids[2];
            }
            private set
            {
                ids[2] = value;
            }
        }

        public void SetFollowingList(XElement friends,XElement followers)
        {
            this.friends = friends.Elements("id").Select(id => Convert.ToInt32(id.Value)).ToList();
            this.followers = followers.Elements("id").Select(id => Convert.ToInt32(id.Value)).ToList();
        }

        public void AddTimeLine(Status item)
        {
            if (!timeLine.Contains(item))
            {
                timeLine.Add(item);
                GetImage(item.user.profileImageUrl);
            }
        }

        public Bitmap GetImage(string url)
        {
            if (profileImage.ContainsKey(url))
            {
                return (profileImage[url]);
            }
            else
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "GET";

                WebResponse responce;
                try
                {
                    responce = req.GetResponse();
                }
                catch (WebException)
                {
                    return new Bitmap(48, 48);
                }

                return (profileImage[url] = new Bitmap(responce.GetResponseStream()));
            }
        }
    }

}
